package com.yc.other.mail;

import java.util.Properties;

import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 邮箱工具
 * @author yuancan
 * @date  2018-03-29 20:14 
 * @since 3.0.0.3
 */
public class EmailUtil {
	
	private static Logger log = LoggerFactory.getLogger(EmailUtil.class);

	/**
	 * 校验邮箱（邮箱账号、密码、pop服务器）
	 * @param pop3Host		pop3服务器地址
	 * @param emailAccount	邮箱账号
	 * @param password		密码
	 * @return
	 */
	public static boolean verifyEamilAccount(String pop3Host, String emailAccount, String password) {
			log.info("校验邮箱账号");
		try {
			// create properties field
			Properties properties = new Properties();

			properties.put("mail.pop3s.host", pop3Host);
			properties.put("mail.pop3s.port", "995");
			properties.put("mail.pop3s.starttls.enable", "true");

			// Setup authentication, get session
			Session emailSession = Session.getInstance(properties, new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(emailAccount, password);
				}
			});
			// emailSession.setDebug(true);

			// create the POP3 store object and connect with the pop server
			Store store = emailSession.getStore("pop3s");

			store.connect();
			store.close();
			log.info("校验成功");
			return true;
		} catch (Exception e) {
			log.info("邮箱账号信息有误：pop3Host={}, emailAccount={}, password={}", pop3Host, emailAccount, password);
			return false;
		}
	}
	
	public static boolean verifyEamilAccount2(String pop3Host, String emailAccount, String password) {
		log.info("校验邮箱账号");
	try {
		// create properties field
		Properties properties = new Properties();

		properties.put("mail.imaps.host", pop3Host);
		properties.put("mail.imaps.port", "993");
		properties.put("mail.imaps.starttls.enable", "true");

		// Setup authentication, get session
		Session emailSession = Session.getInstance(properties, new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(emailAccount, password);
			}
		});
		// emailSession.setDebug(true);

		// create the POP3 store object and connect with the pop server
		Store store = emailSession.getStore("imaps");

		store.connect();
		store.close();
		log.info("校验成功");
		return true;
	} catch (Exception e) {
		log.info("邮箱账号信息有误：pop3Host={}, emailAccount={}, password={}", pop3Host, emailAccount, password);
		return false;
	}
}
	
	
	public static void main(String[] args) {
		System.out.println(verifyEamilAccount("pop.189.cn", "13758238177@189.cn", "1234qwer"));
//		System.out.println(verifyEamilAccount2("imap.qq.com", "2445003274@qq.com", "YIERSANSIWU"));
	}
	
}
